package com.edu.internship.config.jackson;

import com.edu.internship.util.DateUtils;
import com.edu.internship.util.JsonUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.Locale;

/**
 * code is far away from bug with the animal protecting
 *
 * @author lishiquan
 * @description
 * @date Create in 2019-5-29
 */
@Configuration
public class JacksonConvertConfiguration {

    @Bean
    public ObjectMapper objectMapper() {
        return JsonUtils.getInstance().getObjectMapper();
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializerByType(LocalDateTime.class, new JsonUtils.LocalDateTimeSerializer());
            builder.deserializerByType(LocalDateTime.class, new JsonUtils.LocalDateTimeDeserializer());
            builder.serializerByType(LocalDate.class, new JsonUtils.LocalDateSerializer());
            builder.deserializerByType(LocalDate.class, new JsonUtils.LocalDateDeserializer());
            builder.serializerByType(LocalTime.class, new JsonUtils.LocalTimeSerializer());
            builder.deserializerByType(LocalTime.class, new JsonUtils.LocalTimeDeserializer());
        };
    }

    @Bean
    public Formatter<LocalDateTime> localDateTimeFormatter() {
        return new Formatter<LocalDateTime>() {
            @Override
            public LocalDateTime parse(String text, Locale locale)  {
                return DateUtils.asLocalDateTime(new Date(Long.parseLong(text)));
            }

            @Override
            public String print(LocalDateTime localDateTime, Locale locale) {
                return DateUtils.dateFormatter(localDateTime, "yyyy-MM-dd HH:mm:ss");
            }
        };
    }

    @Bean
    public Formatter<LocalDate> localDateFormatter() {
        return new Formatter<LocalDate>() {
            @Override
            public LocalDate parse(String text, Locale locale)  {
                return LocalDate.parse(text);
            }

            @Override
            public String print(LocalDate localDate, Locale locale) {
                return localDate.toString();
            }
        };
    }

}
